import * as c from '@/services/consts';
import * as api from '@/services/idcApiEvent';
import {
  ArrowRightOutlined,
  CheckCircleFilled,
  CloseCircleFilled,
} from '@ant-design/icons';
import { DrawerForm, ProFormInstance } from '@ant-design/pro-form';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  Badge,
  Space,
  Tag,
} from 'antd';
import React, { useEffect, useRef, useState } from 'react';
// import { useModel } from 'umi';
import dayjs from 'dayjs';
import * as utils from '@/utils/utils';
// import NodeForm from '../VpnServer/components/VpnServerForm';
// import BatchChangeForm from '../VpnServer/components/VpnServerBatchChangeForm';
// import IdcManualForm from '../IdcApiEvent/ManualForm';

type VpnServerFormProps = {
  visible: boolean;
  ver: string | undefined;
  onCancel: () => void;
};

const VpnServerForm: React.FC<VpnServerFormProps> = (props) => {
  const { visible, onCancel, ver } = props;

  if (!visible) {
    return null;
  }

  // const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const actionServerRef = useRef<ActionType>();
  // const { hasRight } = useModel('useAuthModel');
  const [myloading, setMyloading] = useState<boolean>(true);
  const [dataSource, setDataSource] = useState<API.IdcApiEventReport | undefined>(undefined);
  // const [selectIds, setSelectIds] = useState<any[]>([]);
  // const [selectInstanceIds, setSelectInstanceIds] = useState<any[]>([]);
  // const [selectIpIds, setSelectIpIds] = useState<any[]>([]);
  // const [formBatchChangeVisible, setFormBatchChangeVisible] = useState<boolean>(false);
  // const [formNodeVisible, setFormNodeVisible] = useState<boolean>(false);
  // const [formIdcManualVisible, setFormIdcManualVisible] =useState<boolean>(false);

  // const [currentNode, setCurrentNode] = useState<API.VpnServer | undefined>(
  //   undefined,
  // );
  // const [currentNodeId, setCurrentNodeId] = useState<string | undefined>(
  //   undefined,
  // );


  

  const loadData = async () => {
    setMyloading(true);
    const result = await api.report({ key : ver});
    if (result && result.success) {
      setDataSource(result);
    }
    setMyloading(false);
  };

  useEffect(() => {
    loadData();
  }, []);

  



  const columns: ProColumns<API.IdcApiEventResultItemModel>[] = [
    {
      title: '状态',
      align: 'center',
      width: 60,
      dataIndex: 'success',
      sorter: true,
      search: false,
      render: (_, record) => {
        return record.success == true ? (
          <Badge count={<CheckCircleFilled style={{ color: '#52c41a' }} />} />
        ) : (
          <Badge count={<CloseCircleFilled style={{ color: '#f50' }} />} />
        );
      },
    },
    {
      title: '实例ID',
      width:100,
      dataIndex: 'instanceId',
      // render: (_, record) => {
      //   return record.server?.id;
      // },
    },
    {
      title: '实例名称',
      width:200,
      dataIndex: 'serverName',
      // render: (_, record) => {
      //   return record.server?.id;
      // },
    },
    {
      title: 'IDC ID',
      width:200,
      dataIndex: 'idcServerId',
      // render: (_, record) => {
      //   return record.server?.id;
      // },
    },
    {
      title: '结果',
      width:200,
      dataIndex: 'id',
      render: (_, record) => {
        return (
        record.oldIp ?
        <><div>{record.oldIp} <ArrowRightOutlined style={{color:'red'}} /> {record.newIpBlack == true ? <b style={{color:'red'}}>{record.newIp}</b> : record.newIp}</div></>
        :''
        );
      },
    },

  ];

  return (
    <DrawerForm<API.IdcApiEventReport>
      open={visible}
      title={
        <>
          操作结果 <Tag color="blue">版本：{dataSource?.id}</Tag>{' '}
          <Tag color="blue">下发时间：{dayjs(dataSource?.createTime).format('YYYY-MM-DD HH:mm:ss')}</Tag>{' '}
          <Tag color="blue">创建人：{dataSource?.createUser}</Tag>
        </>
      }
      formRef={formRef}
      autoFocusFirstInput
      width={1200}
      // onFinish={handleFormSubmit}
      drawerProps={{
        // forceRender: true,
        // destroyOnClose: true,
        // closable: false,
        onClose: onCancel,
        maskClosable: false,
      }}
      submitter={{
        render: (props, defaultDoms) => {
          return [defaultDoms[0]];
        },
      }}
      loading={myloading}
    >

      {/* <ProTable<API.VpnServerCheckProgress>
        rowKey="client"
        actionRef={actionRef}
        loading={myloading}
        options={{
          fullScreen: false,
          reload: false,
          setting: false,
          density: false,
        }}
        search={false}
        pagination={false}
        columns={clientColumns}
        expandable={undefined}
        dataSource={dataSource?.task?.progresss}
      /> */}



      <ProTable<API.IdcApiEventResultItemModel>
        rowKey="serverId"
        actionRef={actionServerRef}
        headerTitle={<Space style={{width:800}}>
          <b>
            {dataSource?.createTime ? dayjs(new Date()).format('YYYY-MM-DD') !=
              dayjs(dataSource?.createTime).format('YYYY-MM-DD') ? <Tag color="#f50">非当天</Tag> : '' : ''
            }

            {/* <Tag color={utils.getTextRanColor(c.getObjectText(c.IdcApiEventStatusOptions, dataSource?.status))}>
              {c.getObjectText(c.IdcApiEventStatusOptions, dataSource?.status)}
            </Tag> */}
            
            <>
            <Tag color={utils.getTextRanColor(c.getObjectText(c.IdcApiEventActionOptions, dataSource?.action))}>{c.getObjectText(c.IdcApiEventActionOptions, dataSource?.action)}</Tag> 
            </>

            <>
            <Tag color={utils.getTextRanColor(dataSource?.code ?? '')}>{dataSource?.code}</Tag> 
            </>

          </b>
          
          {/* 只显示<Checkbox onChange={(e) => { setDisplayOnlyError(e.target.checked);}} checked={displayOnlyError}><b>出错结果</b></Checkbox>   {c.getObjectText(c.IdcApiEventTypeOptions, dataSource?.code)}
          <Checkbox onChange={(e) => { setDisplayOnlyErrorNode(e.target.checked);}} checked={displayOnlyErrorNode}><b>出错项</b></Checkbox> */}
        </Space>}
        loading={myloading}
        options={{
          fullScreen: false,
          reload: true,
          setting: false,
          density: false,
        }}
        search={false}
        pagination={false}
        columns={columns}
        expandable={undefined}
        dataSource={dataSource?.data}
        toolbar={{
          filter: (
            <>
              <Space
                style={{
                  marginRight: '0px',
                  width:200
                }}
              >
              {/* <span>
                  <Button onClick={async()=>{
                    await loadData();
                  }}>刷新</Button>
              </span> */}
                {/* <span>
                  <Popconfirm
                    key="delete"
                    title="确定要删除吗?"
                    onConfirm={async () => {
                      await handleRemove(dataSource?.task?.id);
                    }}
                  >
                    <Button type="primary">删除</Button>
                  </Popconfirm>
                </span> */}
                {/* <span>
                  <a
                    target="_blank"
                    key="excel"
                    href={`/admin-api/checktask/export?ver=${
                      ver ? ver : dataSource?.id
                    }`}
                  >
                    <ArrowDownOutlined />
                    下载
                  </a>
                </span> */}
              </Space>
            </>
          ),
        }}
        rowSelection={false}
        tableAlertRender={({
          selectedRowKeys,
          selectedRows,
          onCleanSelected,
        }) => (
          <Space size={24}>
            {/* <span>
              已选 {selectedRowKeys.length} 条记录
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消
              </a>
            </span>
            

            <span>
              {hasRight('vpnserver_update') ? (
                <a
                  onClick={async () => {
                    setFormBatchChangeVisible(true);
                  }}
                >
                  修改服务器信息
                </a>
              ) : (
                ''
              )}
            </span>

            <span>
              {hasRight('idcapievent_update') ? (
                <a
                  onClick={async () => {
                    setFormIdcManualVisible(true);
                  }}
                >
                  操作服务器
                </a>
              ) : (
                ''
              )}
            </span>
            

            <span>
              <a
                target="_blank"
                key="export_excel_select"
                href={`/admin-api/checktask/export?ver=${
                  ver ? ver : dataSource?.id
                }${selectIds?.map((val) => {return "&ids=" + val})}`}
              >
                <ArrowDownOutlined />导出Excel
              </a>
            </span> */}
          </Space>
        )}
      />

      {/* <NodeForm
        visible={formNodeVisible}
        loadNodeId={currentNodeId}
        // loadNodeId={currentNode?.id}
        // current={currentNode}
        checks={undefined}
        // defaultGroupIds={groupIds && groupIds.length > 0 ? groupIds : undefined}
        defaultGroupIds={undefined}
        // onSubmit={handleNodeFormSubmit}
        onSubmit={async() =>{
          // setCurrentNode(undefined);
          setCurrentNodeId(undefined);
          setFormNodeVisible(false);
          await loadData();
          // actionServerRef.current?.reload();
        }}
        onCancel={() => {
          setFormNodeVisible(false);
          // setCurrentNode(undefined);
          setCurrentNodeId(undefined);
        }}
      />
      
      
      <BatchChangeForm
        visible={formBatchChangeVisible}
        // onSubmit={handleFormBatchRemarkSubmit}
        selectIds={selectIds}
        onSubmit={async() => {          
          setFormBatchChangeVisible(false);
          await loadData();
          actionServerRef.current?.clearSelected?.();
          // actionServerRef.current?.reload();
        }}
        onCancel={() => {
          setFormBatchChangeVisible(false);
        }}
      />
      
      <IdcManualForm
        visible={formIdcManualVisible}
        instIds={selectInstanceIds}
        groupIds={undefined}
        serverIds={undefined}
        onCancel={() => {
          setFormIdcManualVisible(false);
        }}
        onSubmit={() => {
          setFormIdcManualVisible(false);
          actionServerRef.current?.clearSelected?.();
          // actionRef?.current?.reload();
        }}
      /> */}

    </DrawerForm>
  );
};

export default VpnServerForm;
